import React, { useEffect, useState } from 'react'
import './index.less'
import { UserOutlined, LogoutOutlined, DownloadOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { Dropdown, Avatar, Button, Tooltip } from 'antd'
import { history, useModel } from '@umijs/max'
import { clearLogin, clearAccessToken } from '@/utils/utils'
import DownloadCenter from '@/components/DownloadCenter'

const AvatarMenu = () => {
  const { userInfo, roleList, platformType } = useModel('Global')
  const [items, setItems] = useState<MenuProps['items']>([])
  const [modalOpen, setModalOpen] = useState(false)

  const handleRolePicker = () => {
    clearAccessToken()
    history.replace('/main/rolePicker')
  }

  const handleExitUserLogin = () => {
    clearLogin()
    history.replace('/main/login')
  }

  interface IkeyMap {
    [key: string]: () => void
  }

  const keyMap: IkeyMap = {
    rolePicker: () => handleRolePicker(),
    exit: () => handleExitUserLogin()
  }

  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    keyMap[key]()
  }

  // let items: MenuProps['items'] = [];

  useEffect(() => {
    if (roleList && roleList.length > 1) {
      setItems([
        {
          label: '切换身份',
          key: 'rolePicker',
          icon: <UserOutlined />
        },
        {
          label: '退出登录',
          key: 'exit',
          icon: <LogoutOutlined />
        }
      ])
    } else {
      setItems([
        {
          label: '退出登录',
          key: 'exit',
          icon: <LogoutOutlined />
        }
      ])
    }
  }, [roleList, platformType])

  const menuProps = {
    items,
    onClick: handleMenuClick
  }

  const openDownloadCenter = () => {
    setModalOpen(true)
  }

  return (
    <>
      <Tooltip placement='bottom' title={'导出中心'}>
        <Button
          style={{ background: '#F2F3F5', border: 'none', color: '#4E5969', transform: 'scale(0.8)' }}
          shape='circle'
          icon={<DownloadOutlined />}
          onClick={openDownloadCenter}
        />
      </Tooltip>

      <DownloadCenter modalOpen={modalOpen} setModalOpen={setModalOpen} />
      <Dropdown menu={menuProps} trigger={['click']}>
        <div className={'box'}>
          <span>{userInfo.real_name}</span>
          <Avatar size='small' icon={<UserOutlined />} />
        </div>
      </Dropdown>
    </>
  )
}

export default AvatarMenu
